package com.ncmmall.api.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncmmall.application.util.HttpRequests;
import com.feijin.commons.lang.PropertiesHelps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 微信工具类
 *
 * @author likaikai
 * @date 2019-07-17 15:15
 */
@Component
@Slf4j
public class WechatUtils {

    @Value("${store.path}")
    private String storePath;

    /**
     * 获取AccessToken
     */
    private String getAccessToken() {

        String appId = PropertiesHelps.getValue("wx.appid");
        String secret = PropertiesHelps.getValue("wx.appSecret");

        String result = HttpRequests.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret);

        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getString("errcode") == null || jsonObject.getIntValue("errcode") == 0) {
            return jsonObject.getString("access_token");
        }

        log.error("accessToken: {}", result);
        throw new IllegalArgumentException("获取AccessToken异常");
    }


    /**
     * 生成小程序码
     */
    public String generateQrcode(String page, String scene) throws Exception {

        String accessToken = getAccessToken();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("scene", scene);
        jsonObject.put("page", page);
        jsonObject.put("width", 280);

        HttpResponse response = Request.Post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken)
                .addHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .body(new StringEntity(jsonObject.toString(), "utf-8"))
                .execute()
                .returnResponse();

        if (response.getEntity().getContentType().getValue().toLowerCase().contains("json")) {
            log.error("[生成小程序码异常]: {}", EntityUtils.toString(response.getEntity(), "utf-8"));
            throw new IllegalArgumentException("生成小程序码异常");
        }

        File path = new File(storePath, "code");
        FileUtils.forceMkdir(path);

        String name = System.currentTimeMillis() + ".png";
        FileUtils.copyInputStreamToFile(response.getEntity().getContent(), new File(path, name));

        return name;

    }

}
